﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YJKRevitBase.WinForm;
using YJKRevitDimensionText.VerticalAutoDim.ProgressBar;
using YJKRevitView;

namespace YJKRevitDimensionText.VerticalAutoDim
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	internal class CmdVerticalAutoDim : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			if (Utility.FindWindow(null, "立面标注进度") != IntPtr.Zero)
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
            CmdViewType cmdViewType = (CmdViewType)32;
			if (SwitchView.SetUsableView(cmdViewType, commandData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			if (Utility.GetAllWallByCurAndLinkDoc(commandData.Application.ActiveUIDocument.Document).Count == 0)
			{
				YJKMessageBox.Show("没有可标注的实体!");
				return Autodesk.Revit.UI.Result.Failed;
			}
			WindowHandle owner = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
			using (ProgressBarForm progressBarForm = new ProgressBarForm())
			{
				this.InitPrimaryStatusData(progressBarForm);
				progressBarForm.Show(owner);
				Document document = commandData.Application.ActiveUIDocument.Document;
				IList<ViewPlan> allValidViewPlan = Utility.GetAllValidViewPlan(document, null);
				UIApplication application = commandData.Application;
				VerticalAutoDimManager verticalAutoDimManager = new VerticalAutoDimManager(application, document, allValidViewPlan, progressBarForm);
				try
				{
					verticalAutoDimManager.Init();
					verticalAutoDimManager.DoGeoGroup();
					verticalAutoDimManager.DoDim();
					application.ActiveUIDocument.RefreshActiveView();
					YJKMessageBox.Show("立面标注执行成功!");
				}
				catch (ProgressUserTerminalException)
				{
				}
				catch (Exception)
				{
					YJKMessageBox.Show("立面标注执行过程中发生错误, 命令即将退出!");
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void InitPrimaryStatusData(IDualStatusProgressBarProcess progressbar)
		{
			progressbar.AddSubStatusData(0, new PrimaryStatusData
			{
				StatusValue = "正在进行 楼层搜索..."
			});
			progressbar.AddSubStatusData(1, new PrimaryStatusData
			{
				StatusValue = "正在进行 建筑物外墙搜索..."
			});
			progressbar.AddSubStatusData(2, new PrimaryStatusData
			{
				StatusValue = "正在进行 墙体分析..."
			});
			progressbar.AddSubStatusData(3, new PrimaryStatusData
			{
				StatusValue = "正在进行 门、窗分析..."
			});
			progressbar.AddSubStatusData(4, new PrimaryStatusData
			{
				StatusValue = "正在进行 标注..."
			});
		}
	}
}
